package com.mvc.framework.resolver;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.mvc.framework.servlet.MyModelAndView;

public class ViewResolver {
	private String viewName;
	private File file;

	public ViewResolver(String viewName, File file) {
		this.viewName = viewName;
		this.file = file;
	}

	public String getViewName() {
		return viewName;
	}

	public void setViewName(String viewName) {
		this.viewName = viewName;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	@Override
	public String toString() {
		return "ViewResolver [viewName=" + viewName + ", file=" + file + "]";
	}

	public String parse(MyModelAndView mv) throws Exception {
		StringBuffer sb = new StringBuffer();
		RandomAccessFile randomAccessFile = new RandomAccessFile(this.file, "r");
		try {
			// String readLine = randomAccessFile.readLine();
			String readLine = null;
			while ((readLine = randomAccessFile.readLine()) != null) {
				Matcher matcher = matcher(readLine);
				while (matcher.find()) {
					for (int i = 1; i <= matcher.groupCount(); i++) {
						String paramName = matcher.group(i);
						Object paramValue = mv.getModel().get(paramName);
						if (paramValue == null) {
							continue;
						}
						readLine = readLine.replaceAll("@\\{" + paramName + "\\}", paramValue.toString());
					}
				}
				sb.append(readLine);
			}
		} finally {
			randomAccessFile.close();
		}
		return sb.toString();
	}

	private Matcher matcher(String readLine) {
		Pattern pattern = Pattern.compile("@\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
		Matcher matcher = pattern.matcher(readLine);
		return matcher;
	}
}
